package com.android.panballgame;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.hardware.SensorManager;
import android.media.AudioManager;
import android.os.Bundle;
import android.widget.ImageButton;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;

public class PBMainMenu extends Activity {
	// Activity가 처음 생성될 때 호출된다.
	final PBEngine engine = new PBEngine();
	private int s = 0;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.main);

		DatabaseHandler dbhandler = new DatabaseHandler(this);
		PBEngine.db = dbhandler.getWritableDatabase(); 
	
			// 배경음악 실행			
			PBEngine.musicThread = new Thread() {
				public void run() {
					Intent bgmusic = new Intent(getApplicationContext(), PBMusic.class);
					startService(bgmusic);
					PBEngine.context = getApplicationContext();
				}
				
			};	
				PBEngine.musicThread.start();
				
				 if(check_record(PBEngine.MAIN_TABLE)){
					 db_getmain();
						 
					 PBEngine.isDb =1;
				 }

				if(PBEngine.isMusic == 0)
					s = 1;			

		getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);// 화면 꺼짐 방지

		// 메뉴버튼 옵션 설정
		ImageButton start = (ImageButton) findViewById(R.id.btnStart);// start 버튼
		ImageButton exit = (ImageButton) findViewById(R.id.btnExit);
		ImageButton load = (ImageButton) findViewById(R.id.btnLoad);
		ImageButton option = (ImageButton) findViewById(R.id.btnOption);
		ImageButton rank = (ImageButton) findViewById(R.id.btnRank);

		start.getBackground().setAlpha(PBEngine.MENU_BUTTON_ALPHA);
		start.setHapticFeedbackEnabled(PBEngine.HAPTIC_BUTTON_FEEDBACK);

		exit.getBackground().setAlpha(PBEngine.MENU_BUTTON_ALPHA);
		exit.setHapticFeedbackEnabled(PBEngine.HAPTIC_BUTTON_FEEDBACK);

		load.getBackground().setAlpha(PBEngine.MENU_BUTTON_ALPHA);
		load.setHapticFeedbackEnabled(PBEngine.HAPTIC_BUTTON_FEEDBACK);

		option.getBackground().setAlpha(PBEngine.MENU_BUTTON_ALPHA);
		option.setHapticFeedbackEnabled(PBEngine.HAPTIC_BUTTON_FEEDBACK);

		rank.getBackground().setAlpha(PBEngine.MENU_BUTTON_ALPHA);
		rank.setHapticFeedbackEnabled(PBEngine.HAPTIC_BUTTON_FEEDBACK);

		start.setOnClickListener(new OnClickListener() {// start 버튼
			public void onClick(View v) {
				// 게임 시작!
				if(check_record(PBEngine.LEVEL_TABLE)){					
					 db_getlevel();
					showDialog(PBEngine.NOTICE_DIALOG);
				}
				else{
					PBEngine.level = 1;
					Intent game1 = new Intent(getApplicationContext(), PBGame.class);
					PBMainMenu.this.startActivity(game1);
				}				
			}
		});
		exit.setOnClickListener(new OnClickListener() {// end버튼
			public void onClick(View v) {
				boolean clean = false;
				clean = engine.onExit(v);
				if (clean) {
					int pid = android.os.Process.myPid();
					android.os.Process.killProcess(pid);
				}
			}
		});

		option.setOnClickListener(new OnClickListener() {// option 버튼
			public void onClick(View v) {
				Intent option = new Intent(getApplicationContext(), PBOption.class);
				PBMainMenu.this.startActivity(option);
			}
		});
		load.setOnClickListener(new OnClickListener() {// load 버튼
			public void onClick(View v) {
				Intent load = new Intent(getApplicationContext(), PBLoad.class);
				PBMainMenu.this.startActivity(load);
			
			}
		});
		rank.setOnClickListener(new OnClickListener() {// rank 버튼
			public void onClick(View v) {							
				Intent rank = new Intent(getApplicationContext(), PBRanking.class);
				PBMainMenu.this.startActivity(rank);
			}
		});	
		
	}

	@Override
	public boolean onKeyDown(int KeyCode, KeyEvent event) {
		switch (KeyCode) {
		case KeyEvent.KEYCODE_BACK:// 뒤로가기 버튼으로 종료
			new AlertDialog.Builder(this).setTitle("종료").setMessage("종료 하시겠습니까?").setCancelable(false)
			.setPositiveButton("yes", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int whichButton) {
					boolean clean = false;
					clean = engine.onExit();
					if (clean) {
						int pid = android.os.Process.myPid();
						android.os.Process.killProcess(pid);
					}
					System.exit(0);
				}
			}).setNegativeButton("no", null).show();
			return false;
		default:
			return false;
		}
	}
	
	@Override
	protected Dialog onCreateDialog(int id) {
		// TODO Auto-generated method stub
		Dialog dialog = null;
		switch (id) {
		case PBEngine.NOTICE_DIALOG:
			dialog = loaddialog();			
			break;
			default:
				dialog = null;
		}	
		return dialog;
	}
	
	public Dialog loaddialog(){
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		
		builder.setTitle("알림").setMessage("이전 데이터가 있습니다. 이어 하시겠습니까?").setCancelable(false)
			.setPositiveButton("yes", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int whichButton) {				
					PBEngine.useDb = 1;
					Intent game = new Intent(getApplicationContext(), PBGame.class);
				    startActivity(game);
				}
			}).setNegativeButton("no",new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int whichButton) {
					dialog.cancel();				
					PBEngine.time = 0;
					PBEngine.time_level1 = 0;
					PBEngine.time_level2 = 0;
					PBEngine.time_level3 = 0;
					PBEngine.useDb = 0;
					PBEngine.level = 1;
					Intent game = new Intent(getApplicationContext(), PBGame.class);
				    startActivity(game);
				}
			});
		return builder.create();
	}
	
	public boolean check(String name){//테이블이 있나 체크
		Cursor c = PBEngine.db.rawQuery("SELECT name FROM sqlite_master WHERE type = 'table'", null);
		if(c.moveToFirst()){
			c.close();
			return true;
		}			
		else
			return false;
	}
	
	public static boolean check_record(String table){//해당 레코드가 있나 체크
		Cursor c = PBEngine.db.query(false, PBEngine.MAIN_TABLE, null, "id == '1'", null, null, null, null, null);
		if(c.getCount() > 0){
			c.close();
			return true;
		}
		else
			return false;
	}
	public static boolean check_record1(String table){//해당 레코드가 있나 체크
		Cursor c = PBEngine.db.query(false, PBEngine.LEVEL_TABLE, null, "id_level == '1'", null, null, null, null, null);
		if(c.getCount() > 0){
			c.close();
			return true;
		}
		else
			return false;
	}
	public static void db_addmain(){
		ContentValues values = new ContentValues();
		values.put("id", 1);
		values.put("level", PBEngine.level);//레벨이 달라지면 레벨만 레코드에 업데이트 해야함
		values.put("sound", PBEngine.isSound);
		values.put("music", PBEngine.isMusic);
		
		PBEngine.db.insert(PBEngine.MAIN_TABLE, "", values);//해당 테이블에 레코드 추가
		PBEngine.isDb = 1;
	}
	
	public static void db_updatemain(){	
		ContentValues values = new ContentValues();
		values.put("level", PBEngine.level);
		values.put("sound", PBEngine.isSound);
		values.put("music", PBEngine.isMusic);
		
		PBEngine.db.update(PBEngine.MAIN_TABLE, values, "id == '1'", null);
	}
	
	@SuppressLint("NewApi")
	public static void db_getmain(){
		Cursor c = PBEngine.db.query(false, PBEngine.MAIN_TABLE, new String[]{"level", "sound"}, "id == '1'", null, null, null, null, null);
		c.moveToNext();
		PBEngine.level = c.getInt(0);
		PBEngine.isSound = c.getInt(1);
		c.close();
	}
	public static void db_addlevel(){//부르기전에 메인테이블 먼저 겟 하기 + 정보 받아와야 할듯
		ContentValues values = new ContentValues();
		values.put("id_level", 1);//참조키
		values.put("time_level1", PBEngine.time_level1);
		values.put("time", PBEngine.time);
		values.put("remain", PBEngine.remain);
		if(PBEngine.level >= 3){
			values.put("item2", PBEngine.item2);
			values.put("coin8", PBEngine.drawcoin[7]);
			values.put("coin9", PBEngine.drawcoin[8]);
			values.put("time_level3", PBEngine.time_level3);
		}
		if(PBEngine.level >= 2){
			values.put("time_level2", PBEngine.time_level2);
			values.put("itemloc", PBEngine.itemLoc);
			values.put("item1", PBEngine.item1);
			values.put("coin6", PBEngine.drawcoin[5]);
			values.put("coin7", PBEngine.drawcoin[6]);
		}
		values.put("ballx", PBEngine.ballx);
		values.put("bally", PBEngine.bally);
		values.put("coinloc", PBEngine.coinLoc);
		values.put("coin1", PBEngine.drawcoin[0]);
		values.put("coin2", PBEngine.drawcoin[1]);
		values.put("coin3", PBEngine.drawcoin[2]);
		values.put("coin4", PBEngine.drawcoin[3]);
		values.put("coin5", PBEngine.drawcoin[4]);		

		PBEngine.db.insert(PBEngine.LEVEL_TABLE , "", values);//해당 테이블에 레코드 추가
		PBEngine.isDb = 1;
	}

public static void db_updatelevel(){	//데이터 덮어쓰기 할때 사용
		ContentValues values = new ContentValues();
		if(PBEngine.level >= 3){
			values.put("time_level3", PBEngine.time_level3);
			values.put("item2", PBEngine.item2);
			values.put("coin8", PBEngine.drawcoin[7]);
			values.put("coin9", PBEngine.drawcoin[8]);
		}
		if(PBEngine.level >= 2){
			values.put("time_level2", PBEngine.time_level2);
			values.put("itemloc", PBEngine.itemLoc);
			values.put("item1", PBEngine.item1);
			values.put("coin6", PBEngine.drawcoin[5]);
			values.put("coin7", PBEngine.drawcoin[6]);
		}
		values.put("remain", PBEngine.remain);
		values.put("time_level1", PBEngine.time_level1);
		values.put("time", PBEngine.time);
		values.put("ballx", PBEngine.ballx);
		values.put("bally", PBEngine.bally);
		values.put("coinloc", PBEngine.coinLoc);
		values.put("coin1", PBEngine.drawcoin[0]);
		values.put("coin2", PBEngine.drawcoin[1]);
		values.put("coin3", PBEngine.drawcoin[2]);
		values.put("coin4", PBEngine.drawcoin[3]);
		values.put("coin5", PBEngine.drawcoin[4]);		
		
		PBEngine.db.update(PBEngine.LEVEL_TABLE, values, "id_level == '1'", null);
	}

	@SuppressLint("NewApi")
	public static void db_getlevel(){
		Cursor c = PBEngine.db.query(false, PBEngine.LEVEL_TABLE, new String[]{"ballx", "bally", "coin1", "coin2", "coin3", "coin4", 
				"coin5", "coin6", "coin7", "coin8", "coin9", "itemloc", "item1", "item2", "coinloc", "remain", "time", 
				"time_level1", "time_level2", "time_level3" }, "id_level == '1'", null, null, null, null, null);
		c.moveToNext();
		if(PBEngine.level >= 3){
			PBEngine.item2 = c.getInt(13);
			PBEngine.drawcoin[7] = c.getInt(9);
			PBEngine.drawcoin[8] = c.getInt(10);
		}
		if(PBEngine.level >= 2){
			PBEngine.itemLoc = c.getInt(11);
			PBEngine.item1 = c.getInt(12);
			PBEngine.drawcoin[5] = c.getInt(7);
		    PBEngine.drawcoin[6] = c.getInt(8);
		}
		PBEngine.ballx = c.getFloat(0);
		PBEngine.bally = c.getFloat(1);
		PBEngine.drawcoin[0] = c.getInt(2);
		PBEngine.drawcoin[1] = c.getInt(3);
		PBEngine.drawcoin[2] = c.getInt(4);
		PBEngine.drawcoin[3]= c.getInt(5);
		PBEngine.drawcoin[4] = c.getInt(6);
		PBEngine.coinLoc = c.getInt(14);
		PBEngine.remain = c.getInt(15);
		PBEngine.time = c.getLong(16);
		PBEngine.time_level1 = c.getLong(17);
		PBEngine.time_level2 = c.getLong(18);
		PBEngine.time_level3 = c.getLong(19);
		
		c.close();
	}
	public static void db_getlevel2(){
		Cursor c = PBEngine.db.query(false, PBEngine.LEVEL_TABLE, new String[]{ "remain", "time"}, "id_level == '1'", null, null, null, null, null);
		c.moveToNext();
	
		PBEngine.remain = c.getInt(0);
		PBEngine.time = c.getLong(1);
		
		c.close();
	}
	public static void db_delete(){//모든 레코드를 지운다
		PBEngine.db.delete(PBEngine.LEVEL_TABLE, "", null);
		PBEngine.db.delete(PBEngine.MAIN_TABLE, "", null);		
		PBEngine.isDb = 0;
	}
}
